package com.atguigu.gulimall.order.web;

import com.alipay.api.AlipayApiException;
import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.PayVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.math.BigDecimal;
import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {
    @Autowired
    AlipayTemplate alipayTemplate;
    @Autowired
    private OrderService orderService;

    @GetMapping(value = "/payOrder",produces = "text/html")
    @ResponseBody
    public String payOrder(@RequestParam("orderSn")String orderSn) throws AlipayApiException {
        //根据订单号封装payVo
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = orderService.listWithItems(orderSn);
        payVo.setTotal_amount(orderEntity.getPayAmount().setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        payVo.setOut_trade_no(orderSn);
        payVo.setBody(orderEntity.getReceiverName());
        payVo.setSubject(orderEntity.getReceiverName());

        //给支付宝服务器发送支付信息
        String pay = alipayTemplate.pay(payVo);

        return pay;
    }

    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = orderService.toTrade();
        model.addAttribute("order",confirmVo);
        return "confirm";
    }

    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes){
        //下单，，创建订单，验证令牌，验证价格，锁定库存
        System.out.println("封装好的vo："+orderSubmitVo);
        SubmitOrderResponseVo responseVo = orderService.submitOrder(orderSubmitVo);
        if(responseVo.getCode()!=0){
            //失败回到提交页面
            String msg="下单失败:";
            switch (responseVo.getCode()){
                case 1: msg+="订单信息过期，请刷新页面再次提交";  break;
                case 2: msg+="商品价格变化，请确认后再次提交"; break;
                case 3: msg+="库存锁定失败，商品库存不足"; break;
            }
            redirectAttributes.addFlashAttribute("error",msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }else{
            //成功来到支付页面
            model.addAttribute("order",responseVo);
            return "pay";
        }
    }
}
